package com.chigga.application.hanlder;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.chigga.common.utils.JwtUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自定义元对象处理器
 * @author DefChigga
 */
@Slf4j
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    @Resource
    private JwtUtil jwtUtil;

    /**
     * 新增时填充
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("开始插入填充...");
        // 填充创建时间
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        // 填充更新时间
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        // 从 redis 从取出并 使用 jwtUtil 解析 token 获取用户名
        // 填充创建人 TODO 从上下文获取
        this.strictInsertFill(metaObject, "createUser", String.class, "chigga");
        // 填充更新人 TODO 从上下文获取
        this.strictInsertFill(metaObject, "updateUser", String.class, "chigga");
        // 填充状态标记
        this.strictInsertFill(metaObject, "status", Boolean.class, true);
        // 填充逻辑删除标记
        this.strictInsertFill(metaObject, "deleted", Boolean.class, false);
        // 填充乐观锁版本号
        this.strictInsertFill(metaObject, "version", Long.class, 1L);
    }

    /**
     * 更新时填充
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("开始更新填充...");
        // 填充更新时间
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        // 填充更新人 TODO 从上下文获取
        this.strictUpdateFill(metaObject, "updateUser", String.class, "chigga1");
    }
}